<template>
  <div class="relative flex items-center flex-grow-0 flex-shrink-0" v-close>
    <card-container
      class="mr-48"
      :parent-id="cardData.id"
      position="left"
      com-active="CardLevel2"
      :isDataDemonstration="isDataDemonstration"
      :isShare="isShare"
    />
    <div
      :id="cardData.id"
      class="flex flex-col p-16 main-card color-333333 text-14"
    >
      <div
        class="relative flex items-center h-32 mb-8 border-b-1 border-cccccc focus-within:border-3d82ea"
      >
        <div
          class="relative flex-shrink-0 mr-8"
          :class="{ 'cursor-pointer': !isShare }"
          @click="codeTypePullDownFun"
        >
          <span class="text-14 color-333333">{{
            codeType === "1" ? "按条码" : "按批次"
          }}</span>

          <img
            alt="icon_search_16"
            :src="require('./assets/icon_arr_16.svg')"
            style="width: 16px; height: 16px; display: inline-block"
            v-if="!isShare"
          />
          <c-transition>
            <div
              class="absolute top-27 transform-origin-center-top"
              @click.stop
              v-if="codeTypePullDown"
            >
              <div class="py-8 bg-white w-90 code-type-options">
                <div
                  v-for="item in codeTypeOptions"
                  :key="item.value"
                  class="h-40 text-center text-14 text-333333 leading-40 hover:bg-F4F6F8"
                  :class="{ 'text-3d82ea': codeType === item.value }"
                  @click="codeTypeSelect(item.value)"
                >
                  {{ item.label }}
                </div>
              </div>
            </div>
          </c-transition>
        </div>
        <c-transition>
          <div
            class="absolute w-full py-4 bg-white top-32 h-168 code-type-options transform-origin-center-top"
            @click.stop
            v-if="fuzzySearchPullDown"
          >
            <div
              v-for="str in fuzzySearchList"
              class="px-8 overflow-hidden text-center cursor-pointer text-14 leading-32 hover:bg-F4F6F8 overflow-ellipsis"
              v-html="searchContentInit(str)"
              @click="handleFuzzySearchClick(str)"
            ></div>
          </div>
        </c-transition>
        <div class="flex-1" @click="mainInputFocus" @dblclick="copy">
          <el-tooltip
            :content="$i18n.t('mind.copyMsg')"
            v-model="copySuccess"
            placement="right"
            manual
          >
            <input
              v-model="maiInput"
              @input.prevent.stop="handleInput"
              @keyup.enter="handleSearch"
              ref="maiInput"
              class="w-full h-32 bg-transparent"
              :placeholder="`请输入${codeType === '1' ? '条码' : '批次'}`"
              :disabled="isShare"
            />
          </el-tooltip>
        </div>
        <img
          alt="icon_del"
          src="./assets/icon_del.svg"
          class="flex-shrink-0 w-16 h-16 ml-8 cursor-pointer"
          @click="handleClean"
          v-if="maiInput.length && !isShare"
        />
        <img
          alt="icon_search_16"
          src="./assets/icon_search_16.svg"
          class="flex-shrink-0 w-16 h-16 ml-4 cursor-pointer"
          @click="handleSearch"
          v-if="maiInput.length && !isShare"
        />
      </div>
      <div
        class="flex mt-8 text-14"
        v-for="item in Object.keys(rootItem).filter((o) => o !== '条码')"
      >
        <span class="leading-24">{{ item }}：</span>
        <LabelCopy class="flex-1 leading-24" :text="rootItem[item]" />
      </div>
    </div>
    <card-container
      class="ml-48"
      :parent-id="cardData.id"
      position="right"
      com-active="CardLevel2"
      :isDataDemonstration="isDataDemonstration"
      :isShare="isShare"
    />
    <div
      id="line-area"
      style="width: inherit; height: inherit; z-index: -10"
      class="absolute top-0 bottom-0 left-0 right-0"
    ></div>
  </div>
</template>

<script>
import { createId } from "@/utils/tools-mind";
import CardContainer from "@/views/mind/components/card-container.vue";
import {
  mindQueryNextNodes,
  mindQueryNodeInfo,
  listByBarcodeOrSn,
} from "@/api/tool/gen.js";
import CTransition from "@/components/CTransition/index.vue";
import LabelCopy from "./common/label-copy.vue";
import byBarCode from "../demonstration-data/by_bar_code.json";
import byBatch from "../demonstration-data/by_batch.json";

export default {
  name: "main-card",
  props: {
    isShare: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      maiInput: "",
      cardData: {},
      rootItem: {},
      // 切换
      codeTypePullDown: false,
      codeType: "1",
      codeTypeOptions: [
        {
          label: "按条码",
          value: "1",
        },
        {
          label: "按批次",
          value: "2",
        },
      ],
      // 模糊搜索
      fuzzySearchTimer: null,
      fuzzySearchPullDown: false,
      fuzzySearchList: [],
      // 复制
      copySuccess: false,
      // 数据演示
      isDataDemonstration: false,
    };
  },
  directives: {
    close(el, binding, vnode) {
      window.addEventListener("click", (e) => {
        if (!el.contains(e.target)) {
          vnode.context.codeTypePullDown = false;
          vnode.context.fuzzySearchPullDown = false;
        }
      });
    },
  },
  components: { CardContainer, CTransition, LabelCopy },
  mounted() {
    this.$store.commit("mind/cleanNodeCards");
    this.cardData = { ...this.$store.state.mind.rootCard };
    this.$refs.maiInput.focus();
  },
  methods: {
    handleInput(e) {
      if (this.isShare) {
        return;
      }
      const { value } = e.target;
      this.codeTypePullDown = false;
      if (value) {
        clearTimeout(this.fuzzySearchTimer);
        this.fuzzySearchTimer = setTimeout(() => {
          this.fuzzySearch(value);
        }, 700);
      } else {
        this.fuzzySearchPullDown = false;
        this.fuzzySearchList = [];
      }
    },
    // 模糊搜索
    fuzzySearch(value) {
      const type = this.codeType === "1" ? 0 : 1;
      listByBarcodeOrSn({ type, str: value }).then((res) => {
        const { result } = res.data;
        this.fuzzySearchList = result;
        if (this.fuzzySearchList.length > 0) {
          this.fuzzySearchPullDown = true;
        }
      });
    },
    handleFuzzySearchClick(str) {
      this.maiInput = str;
      this.handleSearch();
    },
    handleClean() {
      this.$emit("pageInit");
      this.maiInput = "";
      this.fuzzySearchList = [];
      this.rootItem = {};
      this.$store.commit("mind/cleanNodeCards");
      this.$store.commit("mind/changeNodeCard", this.cardData);
      this.$refs.maiInput.focus();
    },
    dataDemonstrationInit() {
      const rootNodeData =
        this.codeType === "1" ? byBarCode["rootNode"] : byBatch["rootNode"];
      const item = rootNodeData.searchResults[0];
      Object.assign(this.cardData, item);
      this.rootItem = item;
      this.$store.commit("mind/changeNodeCard", this.cardData);
      const data =
        this.codeType === "1" ? byBarCode["secondInfo"] : byBatch["secondInfo"];
      this.mindQueryNextNodesDataInit(data);
    },
    handleSearch() {
      this.codeTypePullDown = false;
      this.fuzzySearchPullDown = false;
      if (!this.maiInput) {
        // this.msgError(`请输入${this.codeType === "1" ? "条码" : "批次"}`);
        this.$message.error(`请输入${this.codeType === "1" ? "条码" : "批次"}`)
        this.handleClean();
        return;
      }
      if (this.isDataDemonstration) {
        this.dataDemonstrationInit();
        return;
      }
      // 调接口查根节点条码的信息
      mindQueryNodeInfo(
        { businessCode: this.maiInput, nodeId: this.codeType },
        this.isShare
      )
        .then((res) => {
          if (!res.data.result) {
            this.rootItem = {};
            this.$store.commit("mind/cleanNodeCards");
            this.$store.commit("mind/changeNodeCard", this.cardData);
            // this.msgSuccess(`【${this.maiInput}】暂无条码追溯`);
            this.$message.success(`【${this.maiInput}】暂无条码追溯`)
            return;
          }
          if (res.data.result.searchResults && res.data.result.searchResults.length) {
            const item = res.data.result.searchResults[0];
            Object.assign(this.cardData, item);
            this.rootItem = item;
            this.$store.commit("mind/changeNodeCard", this.cardData);
            // 查询二级信息
            const key = res.data.result.mainField;
            mindQueryNextNodes(
              { businessCode: item[key], nodeId: res.data.result.nodeId },
              this.isShare
            ).then((child) => {
              const { result } = child.data;
              if (result && result.length > 0) {
                this.mindQueryNextNodesDataInit(result);
              }
            });
          } else {
            this.rootItem = {};
            this.$store.commit("mind/cleanNodeCards");
            this.$store.commit("mind/changeNodeCard", this.cardData);
            // this.msgSuccess(`【${this.maiInput}】暂无条码追溯`);
            this.$message.success(`【${this.maiInput}】暂无条码追溯`)
          }
        })
        .finally(() => {
          this.$refs.maiInput.blur();
        });
    },
    mindQueryNextNodesDataInit(data) {
      data.forEach((v) => {
        const { labelList } = v;
        this.$set(v, "id", createId());
        this.$set(v, "type", "card-category");
        this.$set(v, "title", labelList.toString());
        this.$set(v, "active", false);
        this.$set(v, "containerBg", "");
        this.$set(v, "parent", [this.cardData.id]);
        this.$set(v, "position", "right");
        if (labelList.toString() === "原材料") {
          this.$set(v, "position", "left");
        }
      });
      this.$store.commit("mind/cleanNodeCards");
      this.$store.commit("mind/addNodeCards", data);
    },
    searchContentInit(label) {
      const index = label.indexOf(this.maiInput);
      if (index === -1) {
        return `<span>${label}<span>`;
      }
      const indexOther = index + this.maiInput.length;
      return `<span>${label.substr(
        0,
        index
      )}</span><span class="text-3d82ea">${label.substr(
        index,
        this.maiInput.length
      )}</span><span>${label.substr(
        indexOther,
        label.length - indexOther
      )}</span>`;
    },
    // 类型选择
    codeTypePullDownFun() {
      this.fuzzySearchPullDown = false;
      if (this.isShare) {
        return;
      }
      this.codeTypePullDown = !this.codeTypePullDown;
    },
    codeTypeSelect(value) {
      this.$store.commit("mind/SET_CODE_TYPE", value);
      this.codeType = value;
      this.codeTypePullDown = false;
      if (this.isDataDemonstration) {
        this.dataDemonstration();
      }
      if (this.maiInput) {
        this.rootItem = {};
        this.$store.commit("mind/cleanNodeCards");
        this.$store.commit("mind/changeNodeCard", this.cardData);
        if (!this.isDataDemonstration) {
          this.$refs.maiInput.focus();
        }
        this.handleSearch();
      }
    },
    // 复制
    copy() {
      if (!this.maiInput) {
        return;
      }
      let cInput = document.createElement("input");
      cInput.value = this.maiInput;
      document.body.appendChild(cInput);
      cInput.select();
      document.execCommand("copy");
      this.copySuccess = true;
      setTimeout(() => {
        this.copySuccess = false;
      }, 1000);
      document.body.removeChild(cInput);
    },
    // 获取焦点
    mainInputFocus() {
      if (this.isShare) {
        return;
      }
      this.isDataDemonstration = false;
      this.$refs.maiInput.focus();
      if (this.maiInput && this.fuzzySearchList.length > 0) {
        this.fuzzySearchPullDown = true;
        this.codeTypePullDown = false;
      }
    },
    // 数据演示
    dataDemonstration() {
      this.$emit("pageInit");
      this.isDataDemonstration = true;
      if (this.codeType === "1") {
        this.maiInput = "0752A000101103-221017010";
      } else {
        this.maiInput = "MO2210170004-001";
      }
      this.handleSearch();
    },
  },
};
</script>

<style lang="scss" scoped>
.main-card {
  width: 288px;
  min-height: 180px;
  background: linear-gradient(180deg, #f3f3f5 0%, #ffffff 100%);
  box-shadow: 0 8px 16px 1px rgba(11, 45, 97, 0.16);
  border-radius: 4px 4px 4px 4px;

  .bg-transparent {
    background-color: transparent;
  }

  input:focus-visible {
    outline: none;
  }
}

.code-type-options {
  box-shadow: 0px 8px 16px 1px rgba(11, 45, 97, 0.16);
}
</style>
